package com.luych.oauth2Module.service;

import com.luych.oauth2Module.entitey.Oauth2Code;
import com.luych.oauth2Module.entitey.Oauth2Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

@Service
public class Oauth2TokenService {

    private final RestTemplate restTemplate;

    @Autowired
    public Oauth2TokenService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public void saveAuthenticationCode(String clientId, String code, String userId, String redirectUrl, String scope) {
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        params.add("userId", userId);
        params.add("redirectUrl", redirectUrl);
        params.add("scope", scope);
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(params);
        ResponseEntity<String> responseEntity = restTemplate.exchange(
                "http://OAUTH2CENTER/oauth2/authentication/code/{clientId}/{code}",
                HttpMethod.PUT, httpEntity, String.class, clientId, code);
        if (!responseEntity.getStatusCode().equals(HttpStatus.OK)) {
            throw new RestClientException("[" + responseEntity.getStatusCode().value() + "]：" + responseEntity.getBody());
        }
    }

    public Oauth2Code getAuthenticationCode(String clientId, String code) {
        return restTemplate.getForObject("http://OAUTH2CENTER/oauth2/authentication/code/{clientId}/{code}", Oauth2Code.class, clientId, code);
    }

    public void deleteAuthenticationCode(String clientId, String code) {
        restTemplate.delete("http://OAUTH2CENTER/oauth2/authentication/code/{clientId}/{code}", clientId, code);
    }

    public void saveToken(String clientId, String accessToken, String refreshToken, String scope) {
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        params.add("accessToken", accessToken);
        params.add("refreshToken", refreshToken);
        params.add("scope", scope);
        restTemplate.put("http://OAUTH2CENTER/oauth2/token/{clientId}", params, clientId);
    }

    public Oauth2Token getToken(String clientId) {
        return restTemplate.getForObject("http://OAUTH2CENTER/oauth2/access/token/{clientId}", Oauth2Token.class, clientId);
    }

    public String getRefreshToken(String clientId) {
        return restTemplate.getForObject("http://OAUTH2CENTER/oauth2/refresk/token/{clientId}", String.class, clientId);
    }

}
